package com.infore.operation;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.sql.DataSource;

/**
 * @author:wk
 * @date:Created in 10:32 2017\12\15 0015
 */
@Configuration
public class DataSourceConfig {

	@Autowired(required = true)
	private Environment env;
	@Autowired
	WallFilter wallFilter;

	@Bean
	@Primary
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource dataSource() throws SQLException {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setUrl(env.getProperty("spring.datasource.url"));
		dataSource.setUsername(env.getProperty("spring.datasource.data-username"));// 用户
		dataSource.setPassword(env.getProperty("spring.datasource.data-password"));// 密码
		dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
		dataSource.setInitialSize(2);
		dataSource.setMaxActive(20);
		dataSource.setMinIdle(0);
		dataSource.setMaxWait(60000);
		dataSource.setValidationQuery("SELECT 1 ");
		dataSource.setTestOnBorrow(false);
		dataSource.setTestWhileIdle(true);
		dataSource.setPoolPreparedStatements(false);
//		dataSource.setFilters("stat,wall");
		Properties properties = new Properties();
		properties.setProperty("druid.stat.mergeSql", "true");
		properties.setProperty("druid.stat.slowSqlMillis", "5000");
		dataSource.setConnectProperties(properties);
//		List<Filter> filters = new ArrayList<Filter>();
//		filters.add(wallFilter);
//		dataSource.setProxyFilters(filters);
		return dataSource;

	}

	@Bean(name = "wallConfig")
	WallConfig wallFilterConfig() {
		WallConfig wc = new WallConfig();
		wc.setMultiStatementAllow(true);
		wc.setNoneBaseStatementAllow(true);//允许一次执行多条语句
		return wc;
	}

	@Bean(name = "wallFilter")
	@DependsOn("wallConfig")
	WallFilter wallFilter(WallConfig wallConfig) {
		WallFilter wfilter = new WallFilter();
		wfilter.setConfig(wallConfig);
		return wfilter;
	}
}
